'use strict';

var ctrl = module.exports = {};
var debug = require('debug'),
  log = debug('yozh:mo:relation:log'),
  error = debug('yozh:mo:relation:error'),
  verbose = debug('yozh:modmo:relationule:verbose'),
  service = require('./relation.service');

ctrl.find = function *(next) {
  //query data
  var query = this.request.body;
  var options = {};
  if (query.limit) {
    options.limit = query.limit;
  }
  if (query.offset) {
    options.offset = query.offset;
  }
  var relations = yield service.find(query.search, query.projection, options);
  if (relations) {
    this.status = 200;
    this.body = relations;
  } else {
    this.status = 404;
    this.body = 'not found';
  }
};

ctrl.findById = function *(next) {
  //query data
  var relation = yield service.findById(this.params.id);
  if (relation) {
    this.status = 200;
    this.body = relation;
  } else {
    this.status = 404;
    this.body = 'not found';
  }
};

ctrl.create = function *(next) {
  // post data
  var data = this.request.body;
  //
  var relation = yield service.create(data);
  if (relation) {
    this.status = 201;
    this.body = {message: relation};
  } else{
    this.status = 409;
    this.body = {message: 'could not create entity'};
  }
};

ctrl.updateById = function *(next) {
  //query data
  var data = this.request.body;
  var modify = {$set: data};
  var relation = yield service.findByIdAndUpdate(this.params.id, modify);
  if (relation) {
    this.status = 200;
    this.body = {};
  } else {
    this.status = 409;
    this.body = {message: 'could not find an entity'};
  }
};

ctrl.delete = function *(next) {
  //query data
  var data = this.request.body;
  var result = yield service.remove(data);
  if (result) {
    this.status = 200;
    this.body = result;
  } else {
    this.status = 409;
    this.body = {message: 'could not find an entity'};
  }
};

ctrl.deleteById = function *(next) {
  //query data
  var data = this.request.body;
  var result = yield service.findByIdAndRemove(this.params.id);
  if (result) {
    this.status = 200;
    this.body = result;
  } else {
    this.status = 409;
    this.body = {message: 'could not find an entity'};
  }
};
